from nonebot import on_command, CommandSession
from nonebot import on_natural_language,NLPSession,IntentCommand
from jieba import posseg

from .get_weather import get_weather_city


@on_command('weather',aliases=('tq','天气','天气预报','查天气'))
async def weather(session: CommandSession):
    city = session.get('city', prompt = '你想查询哪个城市?')
    weather_report = await get_weather_of_city(city)
    await session.finish(weather_report)
    

@weather.args_parser
async def _(session: CommandSession):
    stripped_arg = session.current_arg_text.strip()
    
    if session.is_first_run:
        if stripped_arg:
            session.state['city'] = stripped_arg
        return
        
    if not stripped_arg:
        session.pause('不能为空,重新输入')
        
    session.state[session.current_key] = stripped_arg
    
# weather的处理    
async def get_weather_of_city(city: str) -> str:
    res = get_weather_city(city)
    return res

#自然语言处理
@on_natural_language(keywords=('天气'),only_to_me=False)
async def _(session:NLPSession):
    #去掉消息首尾的空白符
    stripped_msg = session.msg_text.strip()
    #对消息进行分词和词性标注
    words = posseg.lcut(stripped_msg)

    city = None
    #遍历 posseg.lcut 返回的列表
    for word in words:
        #每个元素是一个 pair 对象，包含 word 和 flag 两个属性，分别表示词和词性
        if word.flag == 'ns':
            city = word.word
            break

    return IntentCommand(90.0,'weather',current_arg=city or '')